iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 16
0
Mobile Development

小孩子才做選擇 ! Flutter & React Native 我全都要系列 第 16

[Day16] 與 Firebase 結合之 F.C.M. (媽~我終於搞定 FCM 了)

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20191002/20104220iFKiadvd2m.png

firebase 的 react-native 套件
react-native-firebase-v6

https://invertase.io/blog/react-native-firebase-v6

https://ithelp.ithome.com.tw/upload/images/20191002/20104220AgfpxoZdaw.png

https://ithelp.ithome.com.tw/upload/images/20191002/20104220Mim28n0FCG.png

https://ithelp.ithome.com.tw/upload/images/20191002/20104220MfylPlwcxg.png

https://ithelp.ithome.com.tw/upload/images/20191002/20104220GAoa8IzLM8.png
https://ithelp.ithome.com.tw/upload/images/20191002/20104220EN4oMIhuhd.png

/* eslint-disable prettier/prettier */
import React from 'react';
import { StyleSheet, Platform, Image, Text, View, ScrollView ,Alert} from 'react-native';

import firebase, { RemoteMessage } from 'react-native-firebase';
import AsyncStorage from '@react-native-community/async-storage';


const iosConfig = {
//////你的設定
};

const itHelpApp = firebase.initializeApp(iosConfig);



export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      isSigninInProgress: "",

    };
  }


   componentDidMount() {
    // console.log('User APNS Token:', firebase.messaging().getAPNSToken());
    const fcmToken =  firebase.messaging().getToken();
    console.log('User fcm Token:', fcmToken);
    this.updata();
    this.checkPermission();
    this.createNotificationListeners(); //add this line
    this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
      // Process your message as required
  });
  }
  componentWillUnmount() {
    this.notificationListener();
    this.notificationOpenedListener();
    this.messageListener();

  }
  //1
  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }
  //2
  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  //3
  async getToken() {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        // user has a device token
        await AsyncStorage.setItem('fcmToken', fcmToken);
      }
    }
  }

  async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      this.showAlert(title, body);
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      console.log(JSON.stringify(message));
    });
  }

  showAlert(title, body) {
    Alert.alert(
      title, body,
      [
        { text: 'OK', onPress: () => console.log('OK Pressed') },
      ],
      { cancelable: false },
    );
  }

  // async googleLogin() {
  //   try {
  //     // add any configuration settings here:
  //     await GoogleSignin.configure();

  //     const data = await GoogleSignin.signIn();

  //     // create a new firebase credential with the token
  //     const credential = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken)
  //     // login with credential
  //     const firebaseUserCredential = await firebase.auth().signInWithCredential(credential);

  //     console.warn(JSON.stringify(firebaseUserCredential.user.toJSON()));
  //   } catch (e) {
  //     console.error(e);
  //   }
  // }

  render() {
    return (
      <ScrollView>
        <View style={styles.container}>
          {/* <Image source={require('./assets/ReactNativeFirebase.png')} style={[styles.logo]} /> */}
          <Text style={styles.welcome}>
            Welcome to {'\n'} React Native Firebase
          </Text>
          <Text style={styles.instructions}>
            To get started, edit App.js
          </Text>
          {Platform.OS === 'ios' ? (
            <Text style={styles.instructions}>
              Press Cmd+R to reload,{'\n'}
              Cmd+D or shake for dev menu
            </Text>
          ) : (
              <Text style={styles.instructions}>
                Double tap R on your keyboard to reload,{'\n'}
                Cmd+M or shake for dev menu
            </Text>
            )}
          <View style={styles.modules}>
            <Text style={styles.modulesHeader}>The following Firebase modules are pre-installed:</Text>
            {firebase.admob.nativeModuleExists && <Text style={styles.module}>admob()</Text>}
            {firebase.analytics.nativeModuleExists && <Text style={styles.module}>analytics()</Text>}
            {firebase.auth.nativeModuleExists && <Text style={styles.module}>auth()</Text>}
            {/* https://rnfirebase.io/docs/v5.x.x/auth/social-auth */}
            {firebase.config.nativeModuleExists && <Text style={styles.module}>config()</Text>}
            {firebase.crashlytics.nativeModuleExists && <Text style={styles.module}>crashlytics()</Text>}
            {firebase.database.nativeModuleExists && <Text style={styles.module}>database()</Text>}
            {firebase.firestore.nativeModuleExists && <Text style={styles.module}>firestore()</Text>}
            {firebase.functions.nativeModuleExists && <Text style={styles.module}>functions()</Text>}
            {firebase.iid.nativeModuleExists && <Text style={styles.module}>iid()</Text>}
            {firebase.links.nativeModuleExists && <Text style={styles.module}>links()</Text>}
            {firebase.messaging.nativeModuleExists && <Text style={styles.module}>messaging()</Text>}
            {firebase.notifications.nativeModuleExists && <Text style={styles.module}>notifications()</Text>}
            {firebase.perf.nativeModuleExists && <Text style={styles.module}>perf()</Text>}
            {firebase.storage.nativeModuleExists && <Text style={styles.module}>storage()</Text>}
          </View>
          {/* <GoogleSigninButton
            style={{ width: 192, height: 48 }}
            size={GoogleSigninButton.Size.Wide}
            color={GoogleSigninButton.Color.Dark}
            onPress={this.googleLogin}
            disabled={this.state.isSigninInProgress} /> */}
          {/* {this.Todos()} */}
        </View>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // justifyContent: 'center',
    // alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  logo: {
    height: 120,
    marginBottom: 16,
    marginTop: 64,
    padding: 10,
    width: 135,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  modules: {

    margin: 20,
  },
  modulesHeader: {
    fontSize: 16,
    marginBottom: 8,
  },
  module: {
    fontSize: 14,
    marginTop: 4,
    textAlign: 'center',
  }
});


上一篇
[Day15] 與 Firebase 結合之自動上傳 DB 記帳(三)終於可以掃左右兩邊惹
下一篇
[Day17] 與 Firebase 結合之 functions 大法好
系列文
小孩子才做選擇 ! Flutter & React Native 我全都要32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言